package com.mcp.mcpserver.service;

import com.mcp.mcpserver.exception.DataSourceException;
import com.mcp.mcpserver.model.DataSourceModel;
import com.mcp.mcpserver.model.McpRequest;
import com.mcp.mcpserver.model.McpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
/**
 * @author zhangxin569
 * @date 2025/8/6
 */
@Service
public class McpService {

    @Autowired
    private DatabaseService databaseService;

    @Autowired
    private DataSourceManagerService dataSourceManager;

    public McpResponse handleRequest(McpRequest request) {
        String model = request.getModel();
        Map<String, Object> context = request.getContext();
        Map<String, Object> parameters = request.getParameters();

        try {
            if ("Database".equals(model)) {
                return handleDatabaseOperation(context, parameters);
            } else if ("DataSource".equals(model)) {
                return handleDataSourceOperation(context, parameters);
            } else {
                return McpResponse.error("UNSUPPORTED_MODEL", "Unsupported model: " + model);
            }
        } catch (DataSourceException e) {
            return McpResponse.error("DATASOURCE_ERROR", e.getMessage());
        } catch (Exception e) {
            return McpResponse.error("SYSTEM_ERROR", e.getMessage());
        }
    }

    private McpResponse handleDatabaseOperation(Map<String, Object> context, Map<String, Object> parameters) {
        String dataSource = (String) context.get("data_source");
        String operation = (String) context.get("operation");
        String query = (String) parameters.get("query");


        // 从参数中移除 query 键
        Map<String, Object> queryParams = new HashMap<>(parameters);
        queryParams.remove("query");

        // 检查必要参数
        if (dataSource == null) {
            return McpResponse.error("MISSING_PARAMETER", "data_source is required");
        }
        if (operation == null) {
            return McpResponse.error("MISSING_PARAMETER", "operation is required");
        }
        if (query == null) {
            return McpResponse.error("MISSING_PARAMETER", "query is required");
        }

        switch (operation.toLowerCase()) {
            case "select":
                return databaseService.executeQuery(dataSource, query, queryParams);
            case "insert":
            case "update":
            case "delete":
                return databaseService.executeUpdate(dataSource, query, queryParams);
            default:
                return McpResponse.error("UNSUPPORTED_OPERATION", "Unsupported operation: " + operation);
        }
    }

    private McpResponse handleDataSourceOperation(Map<String, Object> context, Map<String, Object> parameters) {
        String action = (String) context.get("action");

        if (action == null) {
            return McpResponse.error("MISSING_ACTION", "action is required");
        }

        switch (action.toLowerCase()) {
            case "add":
                return addDataSource(parameters);
            case "list":
                return McpResponse.success(dataSourceManager.listDataSources());
            default:
                return McpResponse.error("UNSUPPORTED_ACTION", "Unsupported action: " + action);
        }
    }

    /**
     * 添加数据源
     * @param parameters
     * @return
     */
    private McpResponse addDataSource(Map<String, Object> parameters) {
        DataSourceModel config = new DataSourceModel();
        config.setName((String) parameters.get("name"));
        config.setType((String) parameters.get("type"));
        config.setUrl((String) parameters.get("url"));
        config.setUsername((String) parameters.get("username"));
        config.setPassword((String) parameters.get("password"));

        dataSourceManager.addDataSource(config);
        return McpResponse.success("DataSource added: " + config.getName());
    }
}